#include <iostream>
#include "Sock.hpp"
#include "Protocal.hpp"

void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " port\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    Sock sock;
    int sockfd = sock.Socket();
    if (!sock.Connect(sockfd, server_port, server_ip))
    {
        std::cerr << "Connect error" << std::endl;
        exit(1);
    }

    bool quit = false;
    std::string buffer;
    while (true)
    {
        // 1.获取需求
        Request req;
        std::cout << "please Enter: ";
        std::cin >> req._x >> req._op >> req._y;

        // 2.序列化
        std::string s = req.Serialize();

        // 3.添加长度报头
        s = EnCode(s);
        
        // 4.发送给服务端
        Send(sockfd, s);

        // 5.读取数据
        while (true)
        {
            bool res = Recv(sockfd, &buffer);
            if (!res)
            {
                quit = true;
                break;
            }
            std::string package = DeCode(buffer);
            if (package.empty()) continue;
            
            Respense resp;
            resp.Deserialized(package);
            std::string err;
            switch(resp._code)
            {
            case 1:
                err = "除0错误";
                break;
            case 2:
                err = "模0错误";
                break;
            case 3:
                err = "非法错误";
                break;
            default:
                std::cout << resp._x << resp._op << resp._y << " = " << resp._result << " [success]" << std::endl;
                break;
            }

            if (!err.empty())
            {
                std::cerr << err << std::endl;
            }
            break;
        }
    }

    close(sockfd);
    return 0;
}
